package edu.chl.jadetalk.db;

import edu.chl.jadetalk.core.User;
import edu.chl.jadetalk.core.User_;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author jesper
 */
@Stateless
public class UserFacade implements IUserFacade {

    @PersistenceContext(unitName = "jadetalk_pu")
    EntityManager em;

    @Override
    public void create(User user) {
        em.persist(user);
    }

    @Override
    public void edit(User user) {
        em.merge(user);
    }

    @Override
    public void remove(User user) {
        em.remove(em.merge(user));
    }

    @Override
    public User find(Object id) {
        return em.find(User.class, id);
    }

    @Override
    public User findByName(String name) {
		CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<User> query = builder.createQuery(User.class);
        Root<User> userquery = query.from(User.class);
		try {
			return em.createQuery(query.where(builder.equal(userquery.get(User_.username), name))).getSingleResult();
		} catch (Exception e) {
			return null;
		}
    }

    @Override
    public List<User> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(User.class));
        return em.createQuery(cq).getResultList();
    }

    @Override
    public List<User> findByNamePattern(String namepattern) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<User> query = builder.createQuery(User.class);
        Root<User> userquery = query.from(User.class);
        return em.createQuery(query.where(builder.like(userquery.get(User_.username), namepattern))).getResultList();
    }

    @Override
    public int count() {
        CriteriaQuery<Long> cq = em.getCriteriaBuilder().createQuery(Long.class);
        Root<User> rt = cq.from(User.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        TypedQuery<Long> q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
    
    /**
     * For testing purposes.
     * @param em 
     */
    void setEm(EntityManager em) {
        this.em = em;
    }
}
